在指定的目錄下按右鍵選擇ng g service

我們先建立一個tour.service.ts用來串接tour api
這邊先做取得行程列表的功能getTourList()
in tour.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/operators/map';
@Injectable()
export class TourService {
  url:string = "http://localhost:3000/tours"
  constructor(private http:Http) { }
  getTourList() {
    return this.http
      .get(this.url)
      .map((res:Response) => res.json());
  }
}
而這個TourService必需要在TourModle中宣告在provider區塊,我們的TourComponet才能使用這個服務。
// in tour.module.ts
import { TourService } from './tour.service';
@NgModule({
  ...
  providers:[TourService]
})
export class TourModule { }
接下來我們在TourListComponet使用TourService
首先,我們在Constructor宣告private變數注入Service
然後,在ngOnInit(元件初始化)時,利用tourService的getTourList的方法取得行程列表資料。
// in tour-list.component.ts
...
import { TourService } from '../tour.service';
@Component({
  selector: 'app-tour-list',
  templateUrl: './tour-list.component.html',
  styleUrls: ['./tour-list.component.css']
})
export class TourListComponent implements OnInit {
  tourList:any[] = [];
  constructor(private tourService:TourService) { }
  ngOnInit() {
    this.tourService
      .getTourList()
      .subscribe((response) => {
        this.tourList = data;
      });
  }
}
我們可以在tour-list.component.html
先使用<pre>{{tourList|json}}</pre>檢視資料

接下來利用Bootstrap 4 Card的樣式做列表
<div class="container-fluid">
  <div class="card-deck-wrapper">
    <div class="card-deck">
      <div class="card " *ngFor="let tour of tourList">
        <img class="card-img-top" width="100%" [src]="tour.imgurl" alt="tour.name">
        <div class="card-block">
          <h4 class="card-title">{{tour.name}}</h4>
          <h6 class="card-subtitle text-muted">
            <span>地點:{{tour.location}}</span>
          </h6>
          <p class="card-text">價錢:{{tour.price | currency:'TWD'}}</p>
          <a href="#" class="btn btn-primary">檢視</a>
        </div>
      </div>
    </div>
  </div>
</div>

就完成漂亮的行程列表頁面。